//@ts-nocheck
import React from 'react';
import {Router, Route, Link} from 'dva/router'; //就是react-router-dom里的
import dva, {connect, RouterAPI} from 'dva';
import {Dispatch} from "redux";

const app = dva();

interface Counter1State {
  number: number
}

type Counter1Props = Counter1State & {
  dispatch: Dispatch
}

interface Counter2State {
  number: number
}

type Counter2Props = Counter2State & {
  dispatch: Dispatch
}

type CombineState = {
  counter1: Counter1State, counter2: Counter2State
}

//redux里combineReducers
//combineReducers({counter1:counter1,counter2:counter2})
//combineState = {counter1:{number:0},counter2:{number:0}}
const delay = (ms: number) => new Promise((resolve, reject) => {
  setTimeout(function () {
    resolve()
  }, ms)
})
app.model({
  namespace: 'counter1'
  , state: {number: 0}
  , reducers: {
    increment(state) {
      return {number: state.number + 1}
    }
    , decrement(state) {
      return {number: state.number - 1}
    }
  }
  , effects: {
    //需要注意的是如果派发的动作在reducers和effects里都有 那么都会执行 先走reducer再走effect
    * asyncIncrement(action, {call, put}/*←redux-saga/effects*/) {
      yield call(delay, 1000);
      yield put({type: 'increment'})
    }
  }

  //在系统启动的时候会把所有订阅都执行一次
  , subscriptions: {
    changeTitle({history, dispatch}) {
      history.listen(({pathname}/*←location*/) => {
        document.title = pathname
      });
    }
  }
});

app.model({
  namespace: 'counter2'
  , state: {number: 0}
  , reducers: {
    increment(state) {
      return {number: state.number + 1}
    }
    , decrement(state) {
      return {number: state.number - 1}
    }
  }
});


const Counter1 = (props: Counter1Props) => (
  <div>
    <p>{props.number}</p>
    <button onClick={() => props.dispatch({type: 'counter1/increment'})}>+</button>
    <button onClick={() => props.dispatch({type: 'counter1/asyncIncrement'})}>异步+1</button>
    <button onClick={() => props.dispatch({type: 'counter1/decrement'})}>-</button>
  </div>
);

const mapStateToProps1 = (state: CombineState): Counter1State => state.counter1;
const ConnectedCounter1 = connect(mapStateToProps1)(Counter1);


const Counter2 = (props: Counter2Props) => (
  <div>
    <p>{props.number}</p>
    <button onClick={() => props.dispatch({type: 'counter2/increment'})}>+</button>
    <button onClick={() => props.dispatch({type: 'counter2/decrement'})}>-</button>
  </div>
);

const mapStateToProps2 = (state: CombineState): Counter1State => state.counter2;
const ConnectedCounter2 = connect(mapStateToProps2)(Counter2);

app.router((api?: RouterAPI) => {
  let {history, app} = api!;
  return (
    <Router history={history}>
      <>
        <Link to="/counter1">counter1</Link>
        <Link to="/counter2">counter2</Link>
        <Route path="/counter1" component={ConnectedCounter1}/>
        <Route path="/counter2" component={ConnectedCounter2}/>
      </>
    </Router>
  )
});

app.start('#root');
